import { defineStore } from 'pinia'
import { login, loginByPhone } from '~/api/user'
import { storage } from '~/composables/Storage'
import { ACCESS_TOKEN, CURRENT_USER } from '@/utils/enums'

export const useUserStore = defineStore({
    id: 'app-user',
    state: () => ({
        token: storage.get(ACCESS_TOKEN, ''),
        username: '',
        avatar: '',
        userId: 0,
        info: storage.get(CURRENT_USER, {}),
    }),
    getters: {
        getToken() {
            return this.token
        },
        getAvatar() {
            return this.avatar
        },
        getNickname() {
            return this.username
        },
        getUserInfo() {
            return this.info
        },
    },
    actions: {
        setToken(token) {
            this.token = token
        },
        setAvatar(avatar) {
            this.avatar = avatar
        },
        setUserInfo(info) {
            this.info = info
        },
        // 登录
        async loginByPassword(param) {
            try {
                const response = await login(param)
                const { result, code } = response
                if (code === 200) {
                    const ex = 7 * 24 * 60 * 60
                    storage.set(ACCESS_TOKEN, result.token, ex)
                    this.setToken(result.token)
                }
                return Promise.resolve(response)
            }
            catch (e) {
                return Promise.reject(e)
            }
        },
        async loginByPhone(param) {
            try {
                const response = await loginByPhone(param)
                const { result, code } = response
                if (code === 200) {
                    const ex = 7 * 24 * 60 * 60
                    storage.set(ACCESS_TOKEN, result.token, ex)
                    this.setToken(result.token)
                }
                return Promise.resolve(response)
            }
            catch (e) {
                return Promise.reject(e)
            }
        },

        // 登出
        async logout() {
            this.setUserInfo('')
            storage.remove(ACCESS_TOKEN)
            storage.remove(CURRENT_USER)
            return Promise.resolve('')
        },
    },
})
